import SwiftUI

// MARK: - Toast 管理器
class ToastManager: ObservableObject {
    static let shared = ToastManager()
    
    @Published var isShowing = false
    @Published var message = ""
    private var timer: Timer?
    
    func show(message: String, duration: TimeInterval = 2) {
        DispatchQueue.main.async {
            self.message = message
            self.isShowing = true
            self.timer?.invalidate()
            self.timer = Timer.scheduledTimer(withTimeInterval: duration, repeats: false) { _ in
                withAnimation(.smooth) {
                    self.isShowing = false
                }
            }
        }
    }
}

// MARK: - Toast 视图
struct ToastView: View {
    let message: String
    
    var body: some View {
        Text(message)
            .font(.system(size: 15, weight: .medium))
            .padding(.horizontal, 20)
            .padding(.vertical, 12)
            .background(
                RoundedRectangle(cornerRadius: 25)
                    .fill(Color.black.opacity(0.85))
                    .shadow(color: .black.opacity(0.2), radius: 10, x: 0, y: 5)
            )
            .foregroundColor(.white)
            .transition(.opacity) // 只使用透明度过渡
                 .animation(.easeInOut(duration: 0.3), value: message)
    }
}

// MARK: - 全局 Toast 容器
struct ToastContainerView: View {
    @ObservedObject private var manager = ToastManager.shared
    
    var body: some View {
        ZStack {
            if manager.isShowing {
                ToastView(message: manager.message)
                    .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom)
                    .padding(.bottom, 40)
                    .zIndex(999)
            }
        }
    }
}

// MARK: - 视图扩展
extension View {
    /// 在根视图添加（只需要调用一次）
    func toastView() -> some View {
        self.overlay(ToastContainerView())
    }
}

// MARK: - 全局调用方法
//func showToast(_ text: String, duration: Double = 2) {
//    ToastManager.shared.show(message: text, duration: duration)
//}
